package com.idbk.chargestation.activity.charge;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.assist.ActivityHelp;
import com.idbk.chargestation.api.APIForCharge;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonGunChargeStatus;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.bean.JsonQrScan;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.view.EToolbar2;

/**
 * 单枪界面
 * @author zhx
 *
 */
public class ActivitySingleGun extends BaseActivity implements OnClickListener{

	/**
	 * 数据刷新时间
	 */
	public final static int SINGLE_GUN_REFRESH = 5000;

	private TextView mPoint, mSn, mStyle, mCost, mPerformance;
	private TextView mTip, mConnect, mNext, mGun;
	private JsonQrScan mQrScanInfo;
	private Handler handler;
	private JsonGunChargeStatus result;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_single_gun);

		setupView();

		setupData();
	}

	private void setupView() {
		mToolbar2 = (EToolbar2) findViewById(R.id.tj_toolbar2);
		mToolbar2.setTitle(getToolBarTitle());
		mToolbar2.getBackView().setOnClickListener(this);

		mPoint = (TextView) findViewById(R.id.point);
		mSn = (TextView) findViewById(R.id.sn);
		mStyle = (TextView) findViewById(R.id.style);
		mCost = (TextView) findViewById(R.id.cost);
		mPerformance = (TextView) findViewById(R.id.performance);
		mTip = (TextView) findViewById(R.id.activity_tip);
		mGun = (TextView) findViewById(R.id.activity_gun);

		mConnect = (TextView) findViewById(R.id.activity_connect);
		mNext = (TextView) findViewById(R.id.textview_next);
		if (mConnect != null && mNext != null) {
			mConnect.setOnClickListener(this);
			mNext.setOnClickListener(this);
		}
	}

	private void setupData() {
		mQrScanInfo = getIntent().getParcelableExtra(JsonQrScan.KEY);
		mPoint.setText(mQrScanInfo.pointName);
		mSn.setText(mQrScanInfo.pileSn);
		mStyle.setText(mQrScanInfo.performance);
		mCost.setText(mQrScanInfo.getPriceTypeString());
		mPerformance.setText(mQrScanInfo.chargeSpeed);

		handler = new Handler();
	}
	
	
	@Override
	protected void onStart() {
		if(AppContext.getInstance().isLogin()) {
			handler.post(runnable);
		}
		super.onStart();
	}

	@Override
	protected void onStop() {
		handler.removeCallbacks(runnable);
		super.onStop();
	}

	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			APIForCharge.getChargeGunStatus(mQrScanInfo.pileSn, new EHttpResponse() {

				@Override
				public void onEResponse(String response) {
					result = GsonUtils.toBean(JsonGunChargeStatus.class, response);
					if (result == null) {
						Toast.makeText(ActivitySingleGun.this, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();

					} else if (result.status == GlobalResult.OK.getStatus()) {
						if (result.gunA == JsonPointPile.STATUS_CHARGING
								|| result.gunA == JsonPointPile.STATUS_FINISH
								|| result.gunA == JsonPointPile.STATUS_WAIT) {
							mGun.setBackgroundResource(R.drawable.ico_charging_gun_connected);
							mTip.setText("连接成功，请点击下一步");
							mTip.setTextColor(ContextCompat.getColor(ActivitySingleGun.this, R.color.tj_text_content_0));
							mConnect.setVisibility(View.GONE);
							mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
							mNext.setClickable(true);

						} else {
							mGun.setBackgroundResource(R.drawable.ico_charging_gun_disconnect);
							mTip.setText("请将充电枪与车辆充电口正确连接");
							mTip.setTextColor(ContextCompat.getColor(ActivitySingleGun.this, R.color.tj_text_content_9));
							mConnect.setVisibility(View.VISIBLE);
							mNext.setBackgroundResource(R.drawable.bg_main_button_sm_black);
							mNext.setClickable(false);
						}
						handler.postDelayed(runnable, SINGLE_GUN_REFRESH);

					} else if (result.status == GlobalResult.TOKEN_INVALID.getStatus()) {
						handler.removeCallbacks(runnable);//停止请求枪刷新
						AppContext.getInstance().clearLoginState();
						jumpToLogin(ActivitySingleGun.this, true);

					} else {
						Toast.makeText(ActivitySingleGun.this, result.message, Toast.LENGTH_SHORT).show();
						handler.postDelayed(runnable, SINGLE_GUN_REFRESH);
					}
				}

				@Override
				public void onEErrorResponse(VolleyError error) {
					handler.postDelayed(runnable, SINGLE_GUN_REFRESH);
					Toast.makeText(ActivitySingleGun.this, R.string.common_tip_resultfail, Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onEFinish() {
					super.onEFinish();
				}
			});
		}
	};

	private void dialogTip() {
		new AlertDialog.Builder(ActivitySingleGun.this)
				.setTitle(R.string.common_dialog_tip)
				.setMessage("是否确定退出当前的操作？")
				.setCancelable(false)
				.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

						finish();
					}
				})
				.setNegativeButton(R.string.common_cancel, null)
				.create().show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		dialogTip();
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.toolbar_back:
				dialogTip();
				break;
			case R.id.activity_connect:
				Intent intent = new Intent(ActivitySingleGun.this, ActivityHelp.class);
				startActivity(intent);
				break;
			case R.id.textview_next:
				goToCharging();
				break;
			default:
				break;
		}
	}

	private void goToCharging() {
		handler.removeCallbacks(runnable);
		if (mQrScanInfo == null) {
			Toast.makeText(this, "参数错误，请返回重新连接！", Toast.LENGTH_SHORT).show();
			return;
		}
		if (mQrScanInfo.pileType == JsonPointPile.PILE_TYPE_DC
				|| mQrScanInfo.pileType == JsonPointPile.PILE_TYPE_DC_DOUBLE_GUN_ASYN
				|| mQrScanInfo.pileType == JsonPointPile.PILE_TYPE_DC_DOUBLE_GUN_SYN
				) {
			//直流
			Intent intent = new Intent(this, ActivityChargingDc.class);
			intent.putExtra("gunNum", 1);
			intent.putExtra(JsonQrScan.KEY, mQrScanInfo);
			intent.putExtra(ActivityChargingDc.KEY_CHARGE_ACTION, ActivityChargingDc.CHARGE_ACTION_WAIT);
			startActivity(intent);
			finish();
		} else if (mQrScanInfo.pileType == JsonPointPile.PILE_TYPE_AC_SINGLE_PHASE
				|| mQrScanInfo.pileType == JsonPointPile.PILE_TYPE_AC_THREE_PHASE
				) {
			//交流
			Intent intent = new Intent(this, ActivityChargingAc.class);
			mQrScanInfo.chargeGun = "01";
			intent.putExtra(JsonQrScan.KEY, mQrScanInfo);
			intent.putExtra(ActivityChargingAc.KEY_CHARGE_ACTION, ActivityChargingAc.CHARGE_ACTION_WAIT);
			startActivity(intent);
			finish();
		} else {
			Toast.makeText(this, "无法判断充电桩类型！", Toast.LENGTH_SHORT).show();
		}
	}
	

}
